import json
from datetime import datetime

from common.json_util import to_dicts, to_dict
from common.oss_upload import get_file_url
from daos.album_broadcast_record_info_dao import add_album_broadcast_record_info, \
    query_album_broadcast_record_info_by_album_info_id, update_album_broadcast_record_info
from daos.album_info_dao import *
from daos.album_record_info_dao import query_album_record_info_by_album_info_id, add_album_record_info, \
    update_album_record_info, delete_album_record_info
from daos.album_record_material_dao import add_album_record_material, query_album_record_material_by_album_info_id, \
    update_album_record_material
from daos.image_library_dao import query_image_library
from models.album_broadcast_record_info import AlbumBroadcastRecordInfo
from models.album_record_info import AlbumRecordInfo
from models.album_record_material import AlbumRecordMaterial
from models.biz_enum import SystemLogModule, Qualification, AlbumStatus, PlayletProductionCost, RecordType
from rules import db_commit, PAGINATION_PAGE_SIZE
from rules.system_log_rule import create_system_log


def search_album_info(pk):
    result = query_album_info(pk)
    return result.to_dict()


def search_album_info_all(pk):
    album_info_dict = dict()
    album_info_orm = query_album_info(pk)
    if album_info_orm:
        album_info_dict = album_info_orm.to_dict()
        album_info_dict['album_status_name'] = AlbumStatus.get_name(album_info_dict.get('album_status'))
        album_info_dict['qualification_name'] = Qualification.get_name(album_info_dict.get('qualification'))

        # 查询封面图
        covers = []
        for covers_dict in album_info_dict.get('covers'):
            file_url = get_file_url(covers_dict.get('file_name'), expires=600)
            cover = {
                "id": covers_dict.get('image_library_id'),
                "title": covers_dict.get('title'),
                "file_url": file_url
            }
            covers.append(cover)
        album_info_dict['covers'] = json.dumps(covers)

        # 查询标签
        album_info_dict['tags'] = json.dumps(album_info_dict.get('tags'))

        # 查询资质信息
        record_info_dicts = to_dict(query_album_record_info_by_album_info_id(album_info_dict.get('id')))
        if record_info_dicts:
            album_info_dict['record_info'] = record_info_dicts
        else:
            album_info_dict['record_info'] = dict(license_num='', registration_num='', ordinary_record_num='',
                                                  key_record_num='')

        # 查询备案材料
        record_material_dicts = to_dict(query_album_record_material_by_album_info_id(album_info_dict.get('id')))
        record_material_dicts['cost_distribution_uri'] = ''
        record_material_dicts['assurance_uri'] = ''
        record_material_dicts['playlet_production_cost_name'] = PlayletProductionCost.get_name(
            record_material_dicts.get('playlet_production_cost'))

        cost_distribution_image_orm = query_image_library(record_material_dicts.get('cost_distribution_image_id'))
        if cost_distribution_image_orm:
            file_url = get_file_url(cost_distribution_image_orm.file_name, expires=600)
            cost_distribution = {
                "id": cost_distribution_image_orm.id,
                "title": cost_distribution_image_orm.title,
                "file_url": file_url
            }
            record_material_dicts['cost_distribution_uri'] = json.dumps(cost_distribution)

        if record_material_dicts.get('assurance_image_id') > 0:
            assurance_image_orm = query_image_library(record_material_dicts.get('assurance_image_id'))
            if assurance_image_orm:
                file_url = get_file_url(assurance_image_orm.file_name, expires=600)
                assurance = {
                    "id": assurance_image_orm.id,
                    "title": assurance_image_orm.title,
                    "file_url": file_url
                }
                record_material_dicts['assurance_uri'] = json.dumps(assurance)
        album_info_dict['record_material'] = record_material_dicts

        # 查询广电备案信息
        broadcast_record_dicts = to_dict(query_album_broadcast_record_info_by_album_info_id(album_info_dict.get('id')))
        broadcast_record_dicts['record_type_name'] = RecordType.get_name(broadcast_record_dicts.get('record_type'))
        album_info_dict['broadcast_record_info'] = broadcast_record_dicts

    return album_info_dict


def search_album_info_with_page(page_index, data_param):
    data_param['page'] = page_index
    data_param['page_size'] = PAGINATION_PAGE_SIZE
    result = query_album_info_with_page(data_param)
    item_dicts = to_dicts(result.items)
    for item in item_dicts:
        item['album_status_name'] = AlbumStatus.get_name(item.get('album_status'))
    result.items = item_dicts
    return result


def create_album_info(form, current_user):
    is_commit = False

    album_info_orm = AlbumInfo()

    album_info_orm.dy_album_id = 0
    album_info_orm.title = form.title.data
    album_info_orm.seq_num = int(form.seq_num.data)
    album_info_orm.release_year = int(form.release_year.data)
    album_info_orm.album_status = form.album_status.data
    album_info_orm.recommendation = form.recommendation.data if form.recommendation.data else ''
    album_info_orm.introduction = form.introduction.data if form.introduction.data else ''
    album_info_orm.qualification = form.qualification.data
    album_info_orm.current_dy_version = ''
    album_info_orm.online_dy_version = ''

    # 新增封面
    covers = []
    album_covers_json = json.loads(form.covers.data)
    for item in album_covers_json:
        image_library_orm = query_image_library(item.get('id'))
        if image_library_orm:
            cover = {
                "image_library_id": image_library_orm.id,
                "title": image_library_orm.title,
                "file_name": image_library_orm.file_name,
                "dy_open_pic_id": image_library_orm.dy_open_pic_id
            }
            covers.append(cover)
    album_info_orm.covers = covers

    # 新增标签
    album_info_orm.tags = json.loads(form.tags.data)

    album_info_orm = add_album_info(album_info_orm, is_commit)

    album_record_info_dict = dict()
    # 资质状态是报审通过时，新增资质信息
    if album_info_orm.qualification == Qualification.APPROVED:
        album_record_info_orm = AlbumRecordInfo()
        album_record_info_orm.album_info_id = album_info_orm.id
        album_record_info_orm.license_num = form.license_num.data if form.license_num.data else ''
        album_record_info_orm.registration_num = form.registration_num.data if form.registration_num.data else ''
        album_record_info_orm.ordinary_record_num = form.ordinary_record_num.data if form.ordinary_record_num.data else ''
        album_record_info_orm.key_record_num = form.key_record_num.data if form.key_record_num.data else ''

        album_record_info_orm = add_album_record_info(album_record_info_orm, is_commit)
        album_record_info_dict = album_record_info_orm.to_dict()

    # 新增备案材料
    album_record_material_orm = AlbumRecordMaterial()
    album_record_material_orm.album_info_id = album_info_orm.id
    album_record_material_orm.name = form.name.data
    album_record_material_orm.duration = int(form.duration.data)
    album_record_material_orm.seqs_count = int(form.seqs_count.data)
    album_record_material_orm.production_organisation = form.production_organisation.data
    album_record_material_orm.director = form.director.data.split(',')
    album_record_material_orm.producer = form.producer.data.split(',')
    album_record_material_orm.actor = form.actor.data.split(',')
    album_record_material_orm.summary = form.summary.data if form.summary.data else ''
    album_record_material_orm.cost_distribution_image_id = json.loads(form.cost_distribution_uri.data).get('id')
    album_record_material_orm.assurance_image_id = json.loads(form.assurance_uri.data).get(
        'id') if form.assurance_uri.data else 0
    album_record_material_orm.playlet_production_cost = form.playlet_production_cost.data
    album_record_material_orm.screen_writer = form.screen_writer.data.split(',') if form.screen_writer.data else []

    album_record_material_orm = add_album_record_material(album_record_material_orm, is_commit)

    # 新增广电备案信息
    album_broadcast_record_info_orm = AlbumBroadcastRecordInfo()
    album_broadcast_record_info_orm.album_info_id = album_info_orm.id
    album_broadcast_record_info_orm.record_type = form.record_type.data
    album_broadcast_record_info_orm.broadcast_record_number = form.broadcast_record_number.data

    album_broadcast_record_info_orm = add_album_broadcast_record_info(album_broadcast_record_info_orm, is_commit)

    album_info_dict = album_info_orm.to_dict()
    album_info_dict['record_info'] = album_record_info_dict
    album_info_dict['record_material'] = album_record_material_orm.to_dict()
    album_info_dict['broadcast_record_info'] = album_broadcast_record_info_orm.to_dict()

    # 添加系统日志
    operation_detail_dict = dict(before_operation=None, after_operation=album_info_dict)
    log_dict = dict(module=SystemLogModule.CREATE_ALBUM_INFO.value, operation_detail=operation_detail_dict,
                    operator=current_user.id)
    create_system_log(log_dict, is_commit)

    if not is_commit:
        db_commit()

    return album_info_dict


def describe_album_info(pk, form, current_user):
    is_commit = False
    now = datetime.now()
    if pk != int(form.album_info_id.data):
        raise Exception('无效参数')

    album_info_orm = query_album_info(pk)
    if not album_info_orm:
        raise Exception('短剧不存在')

    record_info_orm = query_album_record_info_by_album_info_id(album_info_orm.id)
    record_material_orm = query_album_record_material_by_album_info_id(album_info_orm.id)
    broadcast_record_orm = query_album_broadcast_record_info_by_album_info_id(album_info_orm.id)

    album_info_dict = album_info_orm.to_dict()
    album_info_dict['record_info'] = to_dict(record_info_orm)
    album_info_dict['record_material'] = to_dict(record_material_orm)
    album_info_dict['broadcast_record_info'] = to_dict(broadcast_record_orm)

    before_operation = album_info_dict.copy()

    need_update_list = ["last_update_time"]
    if form.title.data != album_info_orm.title:
        album_info_orm.title = form.title.data
        need_update_list.append("title")

    if int(form.seq_num.data) != album_info_orm.seq_num:
        album_info_orm.seq_num = int(form.seq_num.data)
        need_update_list.append("seq_num")

    if int(form.release_year.data) != album_info_orm.release_year:
        album_info_orm.release_year = int(form.release_year.data)
        need_update_list.append("release_year")

    if form.album_status.data != album_info_orm.album_status:
        album_info_orm.album_status = form.album_status.data
        need_update_list.append("album_status")

    if form.recommendation.data != album_info_orm.recommendation:
        album_info_orm.recommendation = form.recommendation.data
        need_update_list.append("recommendation")

    if form.introduction.data != album_info_orm.introduction:
        album_info_orm.introduction = form.introduction.data
        need_update_list.append("introduction")

    if form.qualification.data != album_info_orm.qualification:
        album_info_orm.qualification = form.qualification.data
        need_update_list.append("qualification")

    # 更新封面图
    album_covers_json = json.loads(form.covers.data)
    form_cover_id_s = [item.get('id') for item in album_covers_json]
    orm_cover_id_s = [item.get('image_library_id') for item in album_info_orm.covers]
    if form_cover_id_s != orm_cover_id_s:
        covers = []
        for item in album_covers_json:
            image_library_orm = query_image_library(item.get('id'))
            if image_library_orm:
                cover = {
                    "image_library_id": image_library_orm.id,
                    "title": image_library_orm.title,
                    "file_name": image_library_orm.file_name,
                    "dy_open_pic_id": image_library_orm.dy_open_pic_id
                }
                covers.append(cover)
        album_info_orm.covers = covers
        need_update_list.append("covers")

    # 更新标签
    album_tags_json = json.loads(form.tags.data)
    if album_tags_json != album_info_orm.tags:
        album_info_orm.tags = album_tags_json
        need_update_list.append("tags")

    album_info_orm.last_update_time = now
    update_album_info(album_info_orm, *need_update_list, is_commit=is_commit)

    album_info_dict = to_dict(album_info_orm)
    album_info_dict['record_info'] = to_dict(record_info_orm)
    album_info_dict['record_material'] = to_dict(record_material_orm)
    album_info_dict['broadcast_record_info'] = to_dict(broadcast_record_orm)

    # 更新资质信息
    record_info_need_update_list = ["last_update_time"]
    if form.qualification.data == Qualification.APPROVED.value:
        if record_info_orm:
            license_num = form.license_num.data if form.license_num.data else ''
            if license_num != record_info_orm.license_num:
                record_info_orm.license_num = license_num
                record_info_need_update_list.append("license_num")

            registration_num = form.registration_num.data if form.registration_num.data else ''
            if registration_num != record_info_orm.registration_num:
                record_info_orm.registration_num = registration_num
                record_info_need_update_list.append("registration_num")

            ordinary_record_num = form.ordinary_record_num.data if form.ordinary_record_num.data else ''
            if ordinary_record_num != record_info_orm.ordinary_record_num:
                record_info_orm.ordinary_record_num = ordinary_record_num
                record_info_need_update_list.append("ordinary_record_num")

            key_record_num = form.key_record_num.data if form.key_record_num.data else ''
            if key_record_num != record_info_orm.key_record_num:
                record_info_orm.key_record_num = key_record_num
                record_info_need_update_list.append("key_record_num")

            record_info_orm.last_update_time = now
            update_album_record_info(record_info_orm, *record_info_need_update_list, is_commit=is_commit)

        else:
            record_info_orm = AlbumRecordInfo()
            record_info_orm.album_info_id = album_info_orm.id
            record_info_orm.license_num = form.license_num.data if form.license_num.data else ''
            record_info_orm.registration_num = form.registration_num.data if form.registration_num.data else ''
            record_info_orm.ordinary_record_num = form.ordinary_record_num.data if form.ordinary_record_num.data else ''
            record_info_orm.key_record_num = form.key_record_num.data if form.key_record_num.data else ''

            record_info_orm = add_album_record_info(record_info_orm, is_commit)

        album_info_dict['record_info'] = to_dict(record_info_orm)

    else:
        if record_info_orm:
            delete_album_record_info(record_info_orm.id, is_commit)
            album_info_dict['record_info'] = dict()

    # 更新备案材料
    record_material_need_update_list = ["last_update_time"]
    if form.name.data != record_material_orm.name:
        record_material_orm.name = form.name.data
        record_material_need_update_list.append("name")

    if int(form.duration.data) != record_material_orm.duration:
        record_material_orm.duration = int(form.duration.data)
        record_material_need_update_list.append("duration")

    if int(form.seqs_count.data) != record_material_orm.seqs_count:
        record_material_orm.seqs_count = int(form.seqs_count.data)
        record_material_need_update_list.append("seqs_count")

    if form.production_organisation.data != record_material_orm.production_organisation:
        record_material_orm.production_organisation = form.production_organisation.data
        record_material_need_update_list.append("production_organisation")

    if form.director.data.split(',') != record_material_orm.director:
        record_material_orm.director = form.director.data.split(',')
        record_material_need_update_list.append("director")

    if form.producer.data.split(',') != record_material_orm.producer:
        record_material_orm.producer = form.producer.data.split(',')
        record_material_need_update_list.append("producer")

    if form.actor.data.split(',') != record_material_orm.actor:
        record_material_orm.actor = form.actor.data.split(',')
        record_material_need_update_list.append("actor")

    summary = form.summary.data if form.summary.data else ''
    if summary != record_material_orm.summary:
        record_material_orm.summary = summary
        record_material_need_update_list.append("summary")

    cost_distribution_image_id = json.loads(form.cost_distribution_uri.data).get('id')
    if cost_distribution_image_id != record_material_orm.cost_distribution_image_id:
        record_material_orm.cost_distribution_image_id = cost_distribution_image_id
        record_material_need_update_list.append("cost_distribution_image_id")

    assurance_image_id = json.loads(form.assurance_uri.data).get('id') if form.assurance_uri.data else 0
    if assurance_image_id != record_material_orm.assurance_image_id:
        record_material_orm.assurance_image_id = assurance_image_id
        record_material_need_update_list.append("assurance_image_id")

    if form.playlet_production_cost.data != record_material_orm.playlet_production_cost:
        record_material_orm.playlet_production_cost = form.playlet_production_cost.data
        record_material_need_update_list.append("playlet_production_cost")

    screen_writer = form.screen_writer.data.split(',') if form.screen_writer.data else []
    if screen_writer != record_material_orm.screen_writer:
        record_material_orm.screen_writer = screen_writer
        record_material_need_update_list.append("screen_writer")

    record_material_orm.last_update_time = now
    update_album_record_material(record_material_orm, *record_material_need_update_list, is_commit=is_commit)
    album_info_dict['record_material'] = to_dict(record_material_orm)

    # 更新广电备案信息
    broadcast_record_need_update_list = ["last_update_time"]
    if form.record_type.data != broadcast_record_orm.record_type:
        broadcast_record_orm.record_type = form.record_type.data
        broadcast_record_need_update_list.append("record_type")

    if form.broadcast_record_number.data != broadcast_record_orm.broadcast_record_number:
        broadcast_record_orm.broadcast_record_number = form.broadcast_record_number.data
        broadcast_record_need_update_list.append("broadcast_record_number")

    broadcast_record_orm.last_update_time = now
    update_album_broadcast_record_info(broadcast_record_orm, *broadcast_record_need_update_list, is_commit=is_commit)
    album_info_dict['broadcast_record_info'] = to_dict(broadcast_record_orm)

    # 添加系统日志
    operation_detail_dict = dict(before_operation=before_operation, after_operation=album_info_dict)
    log_dict = dict(module=SystemLogModule.UPDATE_ALBUM_INFO, operation_detail=operation_detail_dict,
                    operator=current_user.id)
    create_system_log(log_dict, is_commit)

    if not is_commit:
        db_commit()

    return
